<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import Sortable from 'sortablejs'
import { api as viewerApi } from 'v-viewer'
import 'viewerjs/dist/viewer.css'

interface Props {
  data?: any[] | never | null
  type?: string
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  type: 'web'
})

const list = ref<any[]>([])

const dragTableRef = ref()

// 拖拽table排序
const initDropTable = () => {
  const el = dragTableRef.value.$el.querySelector('.el-table__body tbody')
  Sortable.create(el, {
    handle: '.move-el', //设置指定列作为拖拽
    onEnd(evt: any) {
      const { newIndex, oldIndex } = evt
      let copyEl = JSON.parse(JSON.stringify(list.value[oldIndex]))
      list.value.splice(oldIndex, 1)
      list.value.splice(newIndex, 0, copyEl)
      list.value = list.value.map((v: any, i: number) => {
        return {
          ...v,
          sort: i
        }
      })
      // console.log(list.value)
    }
  })
}

const initList = () => {
  list.value = props.data || []
  nextTick(() => {
    initDropTable()
  })
}

const getSortResult = () => {
  return list.value.map((item: any) => {
    return {
      id: item.id
    }
  })
}

const previewImg = (url: string) => {
  if (url) {
    viewerApi({
      images: [url],
      options: {
        zIndex: 9999
      }
    })
  }
}

defineExpose({
  getSortResult
})

onMounted(() => {
  initList()
})
</script>

<template>
  <el-table ref="dragTableRef" :data="list" style="width: 50vw" height="50vh" class="custom-table" row-key="id" default-expand-all row-class-name="move-el">
    <el-table-column prop="imageUrl" label="轮播封面图" width="100">
      <template #default="scope">
        <el-image style="width: 60px; height: 60px; cursor: pointer" :src="scope.row.imageUrl" fit="cover" @click="previewImg(scope.row.imageUrl)" />
      </template>
    </el-table-column>
    <el-table-column prop="title" label="轮播图标题" min-width="160" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.title }}
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="发布时间" width="160" show-overflow-tooltip></el-table-column>
  </el-table>
</template>

<style lang="scss" scoped>
.move-el-cursor {
  cursor: pointer;

  img {
    width: 60px;
    height: 60px;
  }
}
</style>
